package org.yly.game.rpggame.domain.model.task.condition;

import java.util.Map;

import org.yly.game.rpggame.domain.model.DomainEventPublisher;
import org.yly.game.rpggame.domain.model.DomainEventSubscriber;
import org.yly.game.rpggame.domain.model.player.PlayerGoodsAdd;
import org.yly.game.rpggame.domain.model.task.AcceptedTask;

/**
 * 获得物品任务需求
 * 
 * @author makefu
 * 
 */
public class GetGoodsCompleteCondition implements TaskCompleteCondition {

	private Map<String, Integer> hasGoodsMap; // 已经有的物品
	
	private boolean isOk = false;
	
	public GetGoodsCompleteCondition(final AcceptedTask task, final Map<String, Integer> needGoodsMap) {
		
		DomainEventPublisher.getInstance().subscribe(new DomainEventSubscriber<PlayerGoodsAdd>() {

			@Override
			public void handleEvent(PlayerGoodsAdd domainEvent) {
				if (needGoodsMap.containsKey(domainEvent.getGoodsId())) {
					if (hasGoodsMap.containsKey(domainEvent.getGoodsId())) {
						hasGoodsMap.put(domainEvent.getGoodsId(),
								hasGoodsMap.get(domainEvent.getGoodsId()) + 1);
					} else {
						hasGoodsMap.put(domainEvent.getGoodsId(), 1);
					}
					for (String mosterId : needGoodsMap.keySet()) {
						Integer deadCount = needGoodsMap.get(mosterId);
						deadCount = deadCount == null ? 0 : deadCount;
						Integer needCount = hasGoodsMap.get(mosterId);
						needCount = needCount == null ? 0 : needCount;
						if (deadCount >= needCount) {
							isOk = true;
							task.checkCompleteCondition();
						}
					}
				}
				
			}

			@Override
			public Class<PlayerGoodsAdd> subscribedToEventType() {
				return PlayerGoodsAdd.class;
			}
		});
	}

	@Override
	public boolean check() {
		return isOk;
	}

	public Map<String, Integer> getHasGoodsMap() {
		return hasGoodsMap;
	}
	
}
